package jiujia;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import okhttp3.*;

import java.io.IOException;
import java.util.Random;

/**
 * @author
 * @date 2021年12月07日 21:39
 * @description
 */
public class Seckill {


    public static final String url = "https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx";

    public static final String Cookie = "ASP.NET_SessionId=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2Mzg4ODc5OTguNjUxODA2OCwiZXhwIjoxNjM4ODkxNTk4LjY1MTgwNjgsInN1YiI6IllOVy5WSVAiLCJqdGkiOiIyMDIxMTIwNzEwMzk1OCIsInZhbCI6ImltWVZBUUlBQUFBUVpqbGtOV1F3Tm1FM01UVTRObVV6T0J4dmNYSTFielZMV2tWNVozaFZWRGxaUjFkUWJGQmlUM05KUkVwckFCeHZcclxuVlRJMldIUXhSRmxIUjBKR05XUnJOVjlhVlZGYVEzVjFSRWRGRFRZeExqRXpPUzQ0TkM0eE16Y0FBQUFBQUFBQSJ9.8SJBC77a4lmqaAdod9oqu8gqL1R40j68mmZOjV02sQM";

    public static final String ZFTSL = "97b98892f15c753056cc057eddd8bd03";


    public static final String PID = "62";//九价

    public static final String ID = "6541";//医院


    public static final String TIME = "2021-12-09";


    public static final String token = Cookie;


    public static final  String MXID = "imYVAT6YAAAeZjQB";

    public static void main(String[] args) throws IOException {


        OkHttpClient okHttpClient = new OkHttpClient();


        Headers headers = new Headers.Builder()
                .add("charset", "utf-8")
                .add("Accept-Encoding", "gzip, deflate, br")
                .add("referer", "https://servicewechat.com/wx2c7f0f3c30d99445/91/page-frame.html")
                .add("cookie", Cookie)
                .add("content-type", "application/json")
                .add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat")
                .add("Host", "cloud.cn2030.com")
                .add("Connection", "Keep-Alive")
                .add("zftsl", ZFTSL).build();
        boolean jiuJiaOpen = false;
        String mixed = "";
        while (!jiuJiaOpen) {
            Response response = getSub(headers);
            if (response.isSuccessful()) {
                String subscribeDateAll = response.body().string();
                JsonObject jsonObject = new Gson().fromJson(subscribeDateAll, JsonObject.class);
                if (jsonObject.get("status").getAsInt() == 200) {
                    JsonArray list = jsonObject.getAsJsonArray("list");
                    if (list != null && list.size() > 0) {
                        jiuJiaOpen = true;
                        // mxid
                        mixed = list.get(0).getAsJsonObject().get("date").getAsString();
                    }else{
                        System.out.println("未请求到具体数据，继续请求");
                        jiuJiaOpen = false;
                    }
                }
            }
        }

        //2.获取验证码信息
        mixed = randomStr(MXID.length());
        Request captchaRequest = new Request.Builder()
                .url(url + "?act=GetCaptcha&mxid="+MXID)
                .headers(headers)
                .get().build();


        Response captchaResponse = okHttpClient.newCall(captchaRequest).execute();
        if (captchaResponse.isSuccessful()) {

            System.out.println("验证码响应结果："+captchaResponse.body().string());
            String guid = "";
            //验证码校对
            boolean verifyFail = true;
            Random random=new Random();
            while (verifyFail) {
                String y = "5";
                String x = String.valueOf(random.nextInt(100));
                Response verify = verify(x, y, "", headers);
                if (verify.isSuccessful()) {
                    String result = verify.body().string();
                    System.out.println("初始验证响应结果：" + result);
                    JsonObject jsonObject = new Gson().fromJson(result, JsonObject.class);
                    if (jsonObject.get("status").getAsInt() == 200) {
                        guid = jsonObject.get("guid").getAsString();
                        verifyFail = false;
                    }else {
                        System.out.println("验证图片响应结果" + result);
                        x = String.valueOf(random.nextInt(100));
                    }
                }
            }

            //保存信息
            Response response = save(guid, MXID, headers);
            if (response.isSuccessful()) {
                System.out.println("请求成功信息："+response.body().string());
            }

        }


    }


    static Response verify(String x, String y, String token,Headers headers) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request verifyRequest = new Request.Builder()
                .url(url + "?act=CaptchaVerify&token="+token+"&x="+x+"&y="+y+"")
                .headers(headers)
                .get().build();

        return okHttpClient.newCall(verifyRequest).execute();


    }

    static Response save(String guid, String mixed,Headers headers) throws IOException {

        OkHttpClient okHttpClient = new OkHttpClient();


//        //构建表单参数
//        FormBody.Builder requestBuild=new FormBody.Builder();
//        //添加请求体
//        RequestBody requestBody=requestBuild
//                .add("act","Save20")
//                .add("birthday","1997-06-22")
//                .add("tel","18384015283")
//                .add("sex","2")
//                .add("cname","程玲")
//                .add("doctype","1")
//                .add("idcard","510521199706220727")
//                .add("mxid",mixed)
//                .add("date",TIME)
//                .add("pid",PID)
//                .add("Ftime","1")
//                .add("guid",guid)
//                .build();



        Request request = new Request.Builder()
                .url(url+"?act=Save20" +
                        "&birthday=1997-06-22" +
                        "&tel=18384015283" +
                        "&sex=2" +
                        "&cname=程铃" +
                        "&doctype=1" +
                        "&idcard=" +
                        "&mxid=" +mixed+
                        "&date=" +TIME+
                        "&pid=" +PID+
                        "&Ftime=1" +
                        "&guid="+guid)
                .headers(headers)
                .get().build();

        return okHttpClient.newCall(request).execute();

    }


    static Response getSub(Headers headers) throws IOException {

        System.out.println("（1）开始访问获取客户订阅日期详细信息：GetCustSubscribeDateDetail");
        OkHttpClient okHttpClient = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url + "?act=GetCustSubscribeDateAll&pid=" + PID + "&id=" + ID + "&scdate=2021-12-09")
                .headers(headers)
                .get().build();

        return okHttpClient.newCall(request).execute();
    }

    static String randomStr(int length) {
        String base = "ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
        String result = "";
        int[] ints = new Random().ints(0, base.length()).limit(length).toArray();
        for (int i = 0; i < ints.length; i++) {
            result +=base.charAt(ints[i]);
        }
        return result;
    }


}
